package com.javaspeak.concurrency.pattern.application;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.log4j.Logger;

import com.javaspeak.concurrency.pattern.actor.AbstractActor;
import com.javaspeak.concurrency.pattern.actor.ActorRegistry;
import com.javaspeak.concurrency.pattern.actor.ActorRegistryImpl;

/**
 * @author John Dickerson
 */
public class StartActorImpl extends AbstractActor implements StartActor {

    public Logger logger = Logger.getLogger( StartActorImpl.class );

    private static BlockingQueue<TradeConfirmation> tradeConfirmations =
            new LinkedBlockingQueue<TradeConfirmation>();

    public void sendTrade( Trade trade ){

        logger.debug( "Sending trade with id: " + trade.getTradeId() );

        ActorRegistry actorRegistry = ActorRegistryImpl.getInstance();

        LogTradeActor logTradeActor =
            ( LogTradeActor )actorRegistry.getActor(
                    LogTradeActor.class );

        logTradeActor.logTrade( trade );
    }


    public TradeConfirmation getTradeConfirmation() {

        try {
            TradeConfirmation tradeConfirmation = tradeConfirmations.take();

            return tradeConfirmation;
        }
        catch( InterruptedException e ){

            logger.error( e );
            return null;
        }
    }


    public void addTradeConfirmation( TradeConfirmation tradeConfirmation ){

        // logger.debug( "Adding TradeConfirmation" );

        try {
            tradeConfirmations.put( tradeConfirmation );
        }
        catch( InterruptedException e ){

            logger.error( e );
        }

        // logger.debug( "Finished adding TradeConfirmation" );
    }
}
